package com.ruoyi.api.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.SendMessage;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.system.domain.DzCode;
import com.ruoyi.system.domain.DzHuiyuan;
import com.ruoyi.system.service.IDzCodeService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.DzXiaoqu;
import com.ruoyi.system.service.IDzXiaoquService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

/**
 * 楼盘小区Controller
 * 
 * @author ruoyi
 * @date 2023-08-16
 */
@RestController
@RequestMapping("/api/xiaoqu")
public class DzXiaoquApiController extends BaseController
{
    @Autowired
    private IDzXiaoquService dzXiaoquService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private IDzCodeService dzCodeService;

    @Autowired
    private ServerConfig serverConfig;
    /**
     * 查询楼盘小区列表
     */
    @GetMapping("/list")
    public TableDataInfo list(DzXiaoqu dzXiaoqu)
    {
        startPage();
        List<DzXiaoqu> list = dzXiaoquService.selectDzXiaoquListWeb(dzXiaoqu);
        return getDataTable(list);
    }

    @PostMapping("/list2")
    public TableDataInfo list2(@RequestBody DzXiaoqu dzXiaoqu)
    {
        System.out.println("#######################"+ JSON.toJSONString(dzXiaoqu));
        startPage();
        List<DzXiaoqu> list = dzXiaoquService.selectDzXiaoquListWeb(dzXiaoqu);
        return getDataTable(list);
    }


    @PostMapping("/alluserlist")
    public TableDataInfo alluserlist(@RequestBody SysUser user)
    {
        List<SysUser> userlist = userService.selectUserList(user);
        return getDataTable(userlist);
    }


    @PostMapping("/vlogin")
    public AjaxResult vlogin(@RequestBody LoginBody loginBody)
    {
        SysUser user =  userService.selectUserByPhone(loginBody.getUsername());


        if(user!=null){
            if(loginBody.getOpenid()!=null){
                user.setOpenid(loginBody.getOpenid());
                userService.updateUser(user);
            }
            boolean isMatch = SecurityUtils.matchesPassword(loginBody.getPassword(),user.getPassword());
            if(isMatch){
                return AjaxResult.success(user.getUserId());
            }else{
                return AjaxResult.error("账号密码错误");
            }
        }else{
            return AjaxResult.error("账号密码错误");
        }
    }




    @PostMapping("/updatename")
    public AjaxResult updatename(@RequestBody SysUser user)
    {
        userService.updateUser(user);
        return AjaxResult.success("操作成功");
    }

    @PostMapping("/updatepass")
    public AjaxResult updatepass(@RequestBody SysUser user)
    {
        String userName = user.getUserName();
//        String password = user.getPassword();
        SysUser user2 =  userService.selectUserByPhone(user.getPhonenumber());
        if (!SecurityUtils.matchesPassword(user.getOldpassword(), user2.getPassword()))
        {
            return AjaxResult.error("修改密码失败，旧密码错误");
        }
        userService.resetUserPwd(userName, SecurityUtils.encryptPassword(user.getPassword()));
        return AjaxResult.success();
    }

    @PostMapping("/sms")
    public AjaxResult sms(@RequestBody DzCode dzCode)
    {

        try {
            int max=10000;
            int min=1000;
            Random random = new Random();
            String code =  (random.nextInt(max - min) + min + 1)+"";
            System.out.println("向手机"+dzCode.getDn()+"发送验证码："+code);
            dzCode.setCode(code);
            dzCode.setIsused(0l);
            dzCodeService.insertDzCode(dzCode);
            SendSmsResponse response = SendMessage.sendSms(dzCode.getDn(), dzCode.getCode());
            if(response.getCode()=="OK"){

                return  AjaxResult.success();
            }else{
                return  AjaxResult.success();
            }

        } catch (ClientException e) {
            return  AjaxResult.success();
        }
    }

    @PostMapping("/v2login")
    public AjaxResult v2login(@RequestBody DzCode code)
    {
        code.setIsused(0l);
        List<DzCode> dzcodelist =  dzCodeService.selectDzCodeListWeb(code);
        if(dzcodelist!=null&&dzcodelist.size()>0){
            SysUser user =  userService.selectUserByPhone(code.getDn());
            if(user!=null){

                if(code.getOpenid()!=null){
                    user.setOpenid(code.getOpenid());
                    userService.updateUser(user);
                }
                DzCode codetemp = dzcodelist.get(0);
                codetemp.setIsused(1l);
                dzCodeService.updateDzCode(codetemp);
                return AjaxResult.success(user.getUserId());
            }else{
                return AjaxResult.error("账号未注册，请先注册");
            }
        }else{
            return AjaxResult.error("验证码无效");
        }
    }


    @GetMapping("/v6login")
    public AjaxResult v6login(String openid)
    {
            SysUser user =  userService.selectUserByOpenid(openid);
            if(user!=null){
                return AjaxResult.success(user.getUserId());
            }else{
                return AjaxResult.error("账号未注册，请先注册");
            }
    }

    @RequestMapping("/wxcallback")
    public void weixinCallback(HttpServletResponse httpServletResponse, @RequestParam("code") String code) {
        RestTemplate restTemplate = new RestTemplate();
        String appid = "wx06da8af3c5c8b36b";
        String secret = "68286c062d488ad08453fe4f8aee4706";

        // 使用code获取access_token
        String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code";
        String responseStr = restTemplate.getForObject(accessTokenUrl, String.class);
        System.out.println("1#######################"+JSON.toJSONString(responseStr));
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> accessTokenResponse = null;
        try {
            accessTokenResponse = objectMapper.readValue(responseStr, new TypeReference<Map<String, Object>>() {});
            System.out.println("2#######################"+JSON.toJSONString(accessTokenResponse));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        if (accessTokenResponse.containsKey("errcode")) {
            return;
        }

        String accessToken = (String) accessTokenResponse.get("access_token");
        String openid = (String) accessTokenResponse.get("openid");
        System.out.println("3#######################"+JSON.toJSONString(openid));
        try {
            httpServletResponse.sendRedirect("http://www.jiangsumingding.com/PC/pages/index.html?openid=" + openid);
        } catch (IOException e) {
            System.out.println("4#######################"+JSON.toJSONString(e));
            e.printStackTrace();
        }
    }




    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file,@RequestParam("userId")Long userId ) throws Exception
    {
        try
        {
            System.out.println("------------------------->"+userId);
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            SysUser user = userService.selectUserById(userId);
            if(user!=null){
                user.setAvatar(fileName);
                userService.updateUser(user);
            }
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }


    @PostMapping("/avatar")
    public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file,@RequestBody SysUser user) throws Exception
    {
        if (!file.isEmpty())
        {
            String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
            if (userService.updateUserAvatar(user.getUserName(), avatar))
            {
                AjaxResult ajax = AjaxResult.success();
                ajax.put("imgUrl", avatar);
                return ajax;
            }
        }
        return AjaxResult.error("上传图片异常，请联系管理员");
    }

    @PostMapping("/getuser")
    public AjaxResult getuser(@RequestBody SysUser query)
    {

        SysUser user =  userService.selectUserById(query.getUserId());

        if(user!=null){
            return AjaxResult.success(user);
        }else{
            return AjaxResult.error("获取用户失败");
        }

    }

    @PostMapping("/zhuce")
    public AjaxResult zhuce(@RequestBody SysUser query)
    {

        SysUser user =  userService.selectUserById(query.getUserId());

        if(user!=null){
            return AjaxResult.success(user);
        }else{
            return AjaxResult.error("获取用户失败");
        }

    }




    @PostMapping("/userlist")
    public TableDataInfo userlist(@RequestBody DzXiaoqu dzXiaoqu)
    {
        System.out.println("#######################"+ dzXiaoqu.getUserids());

        List<SysUser> userlist = new ArrayList<SysUser>();
        if(dzXiaoqu.getUserids()!=null){
            String userarr[] = dzXiaoqu.getUserids().split(",");
            for(String username:userarr){
                SysUser user = userService.selectUserByUserName(username);
                if(user!=null){
                    userlist.add(user);
                }
            }
        }

        return getDataTable(userlist);
    }



    /**
     * 导出楼盘小区列表
     */
    @Log(title = "楼盘小区", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DzXiaoqu dzXiaoqu)
    {
        List<DzXiaoqu> list = dzXiaoquService.selectDzXiaoquListWeb(dzXiaoqu);
        ExcelUtil<DzXiaoqu> util = new ExcelUtil<DzXiaoqu>(DzXiaoqu.class);
        util.exportExcel(response, list, "楼盘小区数据");
    }

    /**
     * 获取楼盘小区详细信息
     */
    @GetMapping(value = "/{xqId}")
    public AjaxResult getInfo(@PathVariable("xqId") Long xqId)
    {
        return AjaxResult.success(dzXiaoquService.selectDzXiaoquByXqId(xqId));
    }

    /**
     * 新增楼盘小区
     */
    @Log(title = "楼盘小区", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DzXiaoqu dzXiaoqu)
    {
        return toAjax(dzXiaoquService.insertDzXiaoqu(dzXiaoqu));
    }

    /**
     * 修改楼盘小区
     */
    @Log(title = "楼盘小区", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DzXiaoqu dzXiaoqu)
    {
        return toAjax(dzXiaoquService.updateDzXiaoqu(dzXiaoqu));
    }

    /**
     * 删除楼盘小区
     */
    @Log(title = "楼盘小区", businessType = BusinessType.DELETE)
	@DeleteMapping("/{xqIds}")
    public AjaxResult remove(@PathVariable Long[] xqIds)
    {
        return toAjax(dzXiaoquService.deleteDzXiaoquByXqIds(xqIds));
    }
}
